import { useState, useEffect } from 'react';
import moment from 'moment';
import { connect } from 'umi';
import { Modal, Button, Spin } from 'antd';
import { useTablePipeline } from 'ali-react-table';
import { TjTable } from '@/pages/ETrade/components';
import { useTRState } from '#/utils/trHooks.jsx';
import styles from './index.less';
import planIcon from '@/assets/img/plan_icon.png';
import planIconDark from '@/assets/img/plan_icon_dark.png';
import planIconGre from '@/assets/img/plan_icon_gre.png';
import { SyncOutlined } from '@ant-design/icons';
import { getLimitInfo } from '../..//services';
import { HttpCode } from '#/utils/contacts';
import emitter from '#/utils/events';

const LimitQuery = ({ powerLimitInfo, type, provinceId }) => {
  const [theme, setTheme] = useState(localStorage.getItem('saas-theme') || 'dark');

  const [state, setState] = useTRState({
    visible: false,
    detail_info: [],
    time: '',
    loading: false,
  });

  useEffect(() => {
    emitter.addListener('onGlobalThemeChange', (e) => {
      setTheme(e.key);
    });
    return () => {
      emitter.removeListener('onGlobalThemeChange', () => {});
    };
  }, []);

  const getColumns = () => {
    let columns = [
      {
        code: 'timeOrder',
        name: '时点',
        align: 'center',
      },
    ];
    let data = Array.from({ length: 96 }).map((_, i) => {
      return { timeOrder: i + 1 };
    });
    if (state.detail_info.length > 0) {
      state.detail_info.map((item) => {
        let obj = {
          code: item.stationName,
          name: item.stationName,
          align: 'center',
          children: [],
        };
        if (item.details.length > 0 && !!item.details[0]?.electricPriceType) {
          obj.children.push({
            name: (
              <>
                <div>电价</div>
                <div>(元/MWh)</div>
              </>
            ),
            align: 'center',
            code: `${item.stationName}_electricPriceType`,
          });
        }
        if (item.details.length > 0 && !!item.details[0]?.electricQuantity) {
          obj.children.push({
            name: (
              <>
                <div>电量</div>
                <div>（MW）</div>
              </>
            ),
            align: 'center',
            code: `${item.stationName}_electricQuantity`,
          });
        }
        columns.push(obj);
        item.details.map((item1) => {
          Array.from({ length: 96 }).map((_, i) => {
            if (i + 1 == item1?.timeOrder) {
              data[i][`${item.stationName}_electricPriceType`] = item1?.electricPriceType;
              data[i][`${item.stationName}_electricQuantity`] = item1?.electricQuantity;
            }
          });
        });
      });
    } else {
      data = [];
    }
    return { dataSource: data, columns };
  };
  const fetch = async () => {
    const res = await getLimitInfo({ provinceId, tradeType: type });
    if (res.statusCode === HttpCode.SUCCESS) {
      setState({
        detail_info: res.data,
        time: moment().format('YYYY.MM.DD HH:mm:ss'),
        loading: false,
      });
    } else {
      setState({ loading: false });
    }
  };
  const pipeline = useTablePipeline({}).input(getColumns()).primaryKey('id');
  return (
    <>
      <Modal
        className={styles.model_detail}
        centered={true}
        title={
          <div className={styles.modalTitle}>
            <img src={theme === 'dark' ? planIconDark : theme === 'gre' ? planIconGre : planIcon} />
            <span className={styles.text}>限额查询</span>
          </div>
        }
        footer={null}
        visible={state.visible}
        onCancel={() => {
          setState({ visible: false });
        }}
      >
        <Spin spinning={state.loading}>
          <div className={styles.flex_row}>
            <div
              className={styles.right_info}
              onClick={() => {
                setState({ loading: true });
                fetch();
              }}
            >
              更新时间：
              {state.time}
              <a>
                <SyncOutlined />
                刷新
              </a>
            </div>
          </div>
          <TjTable
            className={styles.tableBox}
            style={{
              // '--header-bgcolor': '#434749',
              // '--header-color': 'white',
              // '--border-color': 'rgba(255, 255, 255, 0.1)',
              '--header-row-height': '36px',
              '--font-size': '12px',
              // '--cell-border-vertical': '1px solid rgba(255, 255, 255, 0.1)',
              // '--header-cell-border-vertical': '1px solid rgba(255, 255, 255, 0.1)',
              // '--bgcolor': '#222629',
              // '--color': 'white',
              // '--hover-bgcolor': '#222629',
              '--cell-padding': '4px 5px',
              marginTop: '20px',
              // border: '1px solid #444',
              borderRadius: '5px',
            }}
            useOuterBorder={true}
            stickyScrollHeight={10}
            useVirtual={{ horizontal: true, vertical: true, header: false }}
            defaultColumnWidth={100}
            {...pipeline.getProps()}
          />
        </Spin>
      </Modal>
      <Button
        onClick={() => {
          setState({ visible: true, loading: true });
          fetch();
        }}
      >
        限额查询
      </Button>
    </>
  );
};
export default connect(({ interprovincialSpotDeclaration }) => ({
  powerLimitInfo: interprovincialSpotDeclaration.powerLimitInfo,
  type: interprovincialSpotDeclaration.type,
  provinceId: interprovincialSpotDeclaration.provinceId,
}))(LimitQuery);
